# 872. 叶子相似的树

var leafSimilar = function(root1, root2) {
  let oneStr = [],
    twoStr = [];

  getVal(root1, oneStr);
  getVal(root2, twoStr);

  return oneStr.join("+") === twoStr.join("+");

  function getVal(r, arr) {
    if (r === undefined || r === null) return;

    if (!r.left && !r.right) {
      arr.push(r.val);
    } else {
      getVal(r.left, arr);
      getVal(r.right, arr);
    }
  }
};

const root1 = {
  val: 3,
  left: {
    val: 5,
    left: {
      val: 6,
    },
    right: {
      val: 2,
      left: {
        val: 7,
      },
      right: {
        val: 4,
      },
    },
  },
  right: {
    val: 1,
    left: { val: 9 },
    right: { val: 8 },
  },
};

const root2 = {
  val: 3,
  left: {
    val: 5,
    left: { val: 6 },
    right: { val: 7 },
  },
  right: {
    val: 1,
    left: { val: 4 },
    right: {
      val: 2,
      left: { val: 9 },
      right: { val: 8 },
    },
  },
};

console.log(leafSimilar(root1, root2));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Last Updated: 6/27/2023, 7:40:45 PM